#!/bin/bash

#menu list
menu(){
	echo "1.config hostname"
	echo "2.config ip"
	echo "3.show ip and hostname"
	echo "4.exit"
}

#change hostname
host(){
	read -p "please input you change hostname format(name.name):" u_host
	sed -i  "/^HOSTNAME/s/=.*/=${u_host}/" /etc/sysconfig/network 
	hostname ${u_host}
	cat /etc/sysconfig/network
	echo "attention! change hostname need reboot take effect,so you need reboot computer"
}

#config ip
ip(){
#ipfile="/etc/sysconfig/network-scripts/ifcfg-eth0"
ipfile="/root/shiyan/ifcfg-eth0"
[ -f ip.txt ] && echo "the copy ip addredd file already exist" || cat ${ipfile} >ip.txt 
read -p "please input you want config ip address:" u_ip
read -p "please input you want config netmask:" u_mask
read -p "please input you want config gateway:" u_gateway
read -p "please input you want config dns:" u_dns
if [ -z ${u_ip} ];then
	echo "can't emputy"
	exit
fi
echo ${u_ip} |egrep "([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}"
if (( $? ==0 ));then
	sed -i '/^ONBOOT/s/no/yes/' ${ipfile}
	cat ${ipfile} |grep "IPADDR"
	if [[ $? == 0 ]];then
		sed -i "/^IPADDR/s/=.*/=${u_ip}/" ${ipfile}
	else
		sed -i "$a IPADDR=${u_ip}" ${ipfile} 
	fi
	
	cat ${ipfile} |grep "NETMASK"
        if [[ $? == 0 ]];then
                sed -i "/^NETMASK/s/=.*/=${u_mask}/" ${ipfile}
        else
                sed -i "$a NETMASK=${u_mask}" ${ipfile}
        fi
	
	 cat ${ipfile} |grep "GATEWAY"
        if [[ $? == 0 ]];then
                sed -i "/^GATEWAY/s/=.*/=${u_gateway}/" ${ipfile}
        else
                sed -i "$a GATEWAY=${u_gateway}" ${ipfile}
        fi
	
	 cat ${ipfile} |grep "DNS1"
        if [[ $? == 0 ]];then
                sed -i "/^DNS1/s/=.*/=${u_dns}/" ${ipfile}
        else
                sed -i "$a DNS1=${u_dns}" ${ipfile}
        fi
	service network restart $>/dev/null
else
	echo "ip address has error"

fi
}

#show ip and hostname
show(){
	ipfile="/etc/sysconfig/network-scripts/ifcfg-eth0"
	echo -e "\e[34mip address list:\e[0m"
	cat /etc/sysconfig/network
	echo -e "\e[32m hostname:\e[0m"
	cat ${ipfile}
}

#main function
main(){
	while :
	do
	clear 
	menu
	read -p "please input you option:" u_opt
	case $u_opt in
	1)
	host
	;;
	2)
	ip
	;;
	3)
	show
	;;
	4)
	exit
	;;
	*)
	exit
	;;
	esac
	read 
	done
}
main
